<template>
  <div class="diary-page">
    <h2 class="page-title">日记</h2>
    
    <div class="diary-content">
      <!-- 添加日记 -->
      <div v-if="!selectedEntry" class="diary-add">
        <input 
          type="text" 
          v-model="newEntryTitle" 
          placeholder="日记标题 (可选)"
          class="diary-title-input"
        >
        <textarea 
          v-model="newEntryContent" 
          placeholder="写下今天的感悟..."
          class="diary-content-input"
          rows="6"
        ></textarea>
        <button @click="addEntry" class="add-btn" :disabled="!newEntryContent.trim()">
          <i class="fas fa-plus"></i>
          <span>记录</span>
        </button>
      </div>

      <!-- 日记列表 -->
      <transition name="fade" mode="out-in">
        <div v-if="!selectedEntry" class="entry-list">
          <div v-for="(entries, month) in entriesByMonth" :key="month" class="month-section">
            <h3 class="month-title">{{ month }}</h3>
            <ul class="entry-items">
              <li v-for="entry in entries" 
                  :key="entry.id" 
                  class="entry-item" 
                  @click="viewEntry(entry)">
                <div class="entry-item-header">
                  <span class="entry-item-title">{{ entry.title || '无标题日记' }}</span>
                  <span class="entry-item-date">{{ formatListDate(entry.date) }}</span>
                </div>
                <div class="entry-item-summary">{{ getSummary(entry.content) }}</div>
              </li>
            </ul>
          </div>
           <!-- 空状态 -->
          <div v-if="allEntries.length === 0" class="empty-state">
            <i class="fas fa-book-open"></i>
            <p>还没有日记哦，写下第一篇吧！</p>
          </div>
        </div>
      </transition>
      
      <!-- 日记详情 -->
      <transition name="slide" mode="out-in">
        <div v-if="selectedEntry" class="entry-detail">
          <button class="back-btn" @click="selectedEntry = null">
            <i class="fas fa-arrow-left"></i>
            <span>返回日记列表</span>
          </button>
          
          <h3 class="detail-title">{{ selectedEntry.title || '无标题日记' }}</h3>
          <p class="detail-date">{{ formatDetailDate(selectedEntry.date) }}</p>
          <div class="detail-content" v-html="selectedEntry.content.replace(/\n/g, '<br>')"></div>
          
          <div class="detail-actions">
            <button @click="editEntry(selectedEntry)" class="action-btn edit" title="编辑">
              <i class="fas fa-edit"></i>
              <span>编辑</span>
            </button>
            <button @click="deleteEntry(selectedEntry)" class="action-btn delete" title="删除">
              <i class="fas fa-trash-alt"></i>
              <span>删除</span>
            </button>
          </div>
        </div>
      </transition>

       <!-- 编辑对话框 -->
    <div v-if="editingEntry" class="edit-dialog">
      <div class="dialog-content">
        <h3>编辑日记</h3>
         <input 
          type="text" 
          v-model="editingEntry.title" 
          placeholder="日记标题 (可选)"
          class="diary-title-input"
        >
        <textarea 
          v-model="editingEntry.content" 
          placeholder="写下今天的感悟..."
          class="diary-content-input"
          rows="10"
        ></textarea>
        <div class="dialog-actions">
          <button @click="cancelEdit" class="cancel-btn">取消</button>
          <button @click="saveEdit" class="save-btn" :disabled="!editingEntry.content.trim()">保存</button>
        </div>
      </div>
    </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Diary',
  data() {
    return {
      allEntries: [], // 所有日记条目
      newEntryTitle: '',
      newEntryContent: '',
      selectedEntry: null, // 当前选中的日记，用于显示详情
      editingEntry: null // 正在编辑的日记
    }
  },
  computed: {
    entriesByMonth() {
      const grouped = {}
      this.allEntries.forEach(entry => {
        const date = new Date(entry.date)
        const month = date.toLocaleString('zh-CN', { year: 'numeric', month: 'long' })
        if (!grouped[month]) {
          grouped[month] = []
        }
        grouped[month].push(entry)
      })
      // 按月份倒序排序
      return Object.fromEntries(
        Object.entries(grouped).sort((a, b) => {
          const dateA = new Date(a[0].replace('年', '-').replace('月', ''))
          const dateB = new Date(b[0].replace('年', '-').replace('月', ''))
          return dateB - dateA
        })
      )
    }
  },
  methods: {
    addEntry() {
      const title = this.newEntryTitle.trim()
      const content = this.newEntryContent.trim()
      if (!content) return

      const newEntry = {
        id: Date.now(),
        title: title || '', // 如果无标题则为空字符串
        content: content,
        date: new Date().toISOString()
      }

      this.allEntries.unshift(newEntry) // 添加到列表顶部
      this.newEntryTitle = ''
      this.newEntryContent = ''
      this.saveEntries()
    },
    viewEntry(entry) {
      this.selectedEntry = entry
    },
    editEntry(entry) {
      this.editingEntry = { ...entry }; // 复制一份进行编辑
    },
    saveEdit() {
      if (!this.editingEntry?.content.trim()) return;

      const index = this.allEntries.findIndex(e => e.id === this.editingEntry.id);
      if (index !== -1) {
        this.allEntries.splice(index, 1, { ...this.editingEntry }); // 替换旧条目
        this.saveEntries();
        this.selectedEntry = { ...this.editingEntry }; // 更新详情页显示
      }
      this.cancelEdit();
    },
    cancelEdit() {
      this.editingEntry = null;
    },
    deleteEntry(entry) {
      if (confirm('确定要删除这篇日记吗？')) {
        this.allEntries = this.allEntries.filter(e => e.id !== entry.id);
        this.saveEntries();
        if (this.selectedEntry?.id === entry.id) {
          this.selectedEntry = null; // 如果删除的是当前详情页的日记，则返回列表
        }
      }
    },
    getSummary(content) {
      const strippedContent = content.replace(/\s+/g, ' ').trim(); // 移除多余空白
      return strippedContent.substring(0, 100) + (strippedContent.length > 100 ? '...' : '');
    },
    formatListDate(date) {
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    },
     formatDetailDate(date) {
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    saveEntries() {
      localStorage.setItem('diaryEntries', JSON.stringify(this.allEntries));
    },
    loadEntries() {
      const savedEntries = localStorage.getItem('diaryEntries');
      if (savedEntries) {
        try {
          this.allEntries = JSON.parse(savedEntries);
        } catch (e) {
          console.error('Failed to load diary entries:', e);
          this.allEntries = [];
        }
      }
    }
  },
  created() {
    this.loadEntries();
  }
}
</script>

<style scoped>
.diary-page {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.page-title {
  font-size: 2rem;
  margin-bottom: 30px;
  color: var(--dark);
  font-weight: 600;
  text-align: center;
}

.diary-content {
  background: var(--card-bg);
  border-radius: var(--border-radius-md);
  padding: 30px;
  box-shadow: var(--shadow-md);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.5);
}

.diary-add {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
}

.diary-title-input,
.diary-content-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid var(--gray-light);
  border-radius: var(--border-radius-sm);
  font-size: 1rem;
  transition: var(--transition);
  background: white;
}

.diary-title-input:focus,
.diary-content-input:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 24px;
  background: var(--primary);
  color: white;
  border: none;
  border-radius: var(--border-radius-sm);
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: var(--transition);
}

.add-btn:hover:not(:disabled) {
  background: var(--primary-dark);
  transform: translateY(-1px);
}

.add-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 日记列表样式 */
.entry-list {
  margin-top: 24px; /* 给添加区域留出空间 */
}

.month-section {
  margin-bottom: 30px;
}

.month-title {
  font-size: 1.5rem;
  color: var(--primary);
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid var(--primary-light);
  font-weight: 600;
}

.entry-items {
  list-style: none;
  padding: 0;
  margin: 0;
}

.entry-item {
  background: var(--light);
  border-radius: var(--border-radius-sm);
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--gray-light);
  cursor: pointer;
  transition: var(--transition);
}

.entry-item:last-child {
  margin-bottom: 0;
}

.entry-item:hover {
  transform: translateX(5px);
  box-shadow: var(--shadow-md);
  border-color: var(--primary-light);
  background: white;
}

.entry-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.entry-item-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--dark);
}

.entry-item-date {
  font-size: 0.9rem;
  color: var(--gray);
}

.entry-item-summary {
  font-size: 0.95rem;
  color: var(--dark);
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制显示的行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--gray);
}

.empty-state i {
  font-size: 3rem;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 1.1rem;
}

/* 日记详情样式 */
.entry-detail {
  background: var(--light);
  border-radius: var(--border-radius-md);
  padding: 30px;
  box-shadow: var(--shadow-lg);
  backdrop-filter: blur(10px);
  border: 1px solid var(--gray-light);
}

.detail-title {
  font-size: 2rem;
  margin-bottom: 10px;
  color: var(--dark);
  font-weight: 600;
}

.detail-date {
  font-size: 1rem;
  color: var(--gray);
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--gray-light);
}

.detail-content {
  line-height: 1.8;
  color: var(--dark);
  white-space: pre-wrap; /* 保留换行符 */
}

.detail-actions {
  margin-top: 20px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  background: var(--gray-light);
  color: var(--dark);
  border-radius: var(--border-radius-sm);
  font-size: 0.9rem;
  cursor: pointer;
  transition: var(--transition);
}

.action-btn:hover {
  background: var(--gray);
  color: white;
}

.action-btn.edit:hover {
  background: var(--primary-light);
  color: white;
}

.action-btn.delete:hover {
  background: #ef4444;
  color: white;
}

/* 返回按钮 */
.back-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  background: var(--primary);
  color: white;
  border-radius: 50px;
  cursor: pointer;
  font-size: 0.95rem;
  font-weight: 500;
  transition: var(--transition);
  margin-bottom: 25px;
  box-shadow: var(--shadow-sm);
}

.back-btn:hover {
  background: var(--primary-dark);
  transform: translateX(-2px);
  box-shadow: var(--shadow-md);
}

.back-btn i {
  font-size: 0.9rem;
}

/* 编辑对话框样式 */
.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.edit-dialog .dialog-content {
  background: white;
  padding: 24px;
  border-radius: var(--border-radius-md);
  width: 90%;
  max-width: 600px; /* 更宽一些 */
  box-shadow: var(--shadow-lg);
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.edit-dialog .dialog-content h3 {
  margin-bottom: 8px;
  color: var(--dark);
}

.edit-dialog .dialog-actions {
   display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}

.edit-dialog .cancel-btn,
.edit-dialog .save-btn {
  padding: 8px 20px;
  border-radius: var(--border-radius-sm);
  font-size: 0.95rem;
  cursor: pointer;
  transition: var(--transition);
  border: none;
}

.edit-dialog .cancel-btn {
  background: var(--gray-light);
  color: var(--dark);
}

.edit-dialog .save-btn {
  background: var(--primary);
  color: white;
}

.edit-dialog .save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter,
.slide-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .diary-page {
    padding: 15px;
  }

  .page-title {
    font-size: 1.8rem;
    margin-bottom: 25px;
  }

  .diary-content {
    padding: 20px;
  }

  .month-title {
    font-size: 1.3rem;
  }

  .entry-item {
    padding: 12px;
  }

  .entry-item-title {
    font-size: 1rem;
  }

  .entry-item-date {
    font-size: 0.85rem;
  }

  .entry-item-summary {
    font-size: 0.9rem;
  }

  .entry-detail {
    padding: 25px;
  }

  .detail-title {
    font-size: 1.8rem;
  }

  .detail-date {
    font-size: 0.9rem;
    margin-bottom: 20px;
  }

  .detail-content {
    font-size: 0.95rem;
  }

  .back-btn {
    padding: 8px 16px;
    font-size: 0.9rem;
    margin-bottom: 20px;
  }

  .detail-actions {
    flex-direction: column;
    gap: 8px;
    margin-top: 16px;
  }

  .action-btn {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .diary-page {
    padding: 10px;
  }

  .diary-content {
    padding: 15px;
  }

  .entry-item {
    padding: 10px;
  }

  .entry-item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .entry-item-date {
    align-self: flex-start;
  }

  .entry-detail {
    padding: 20px;
  }

  .detail-actions {
    flex-direction: column;
    gap: 8px;
  }

   .edit-dialog .dialog-content {
    padding: 15px;
  }
}

</style> 